package com.hilinos.base.app.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hilinos.base.app.KeyApp;
import com.hilinos.base.service.KeyInfoService;
import com.hilinos.base.user.entity.pojo.KeyInfoPoJo;
import com.hilinos.common.entity.BaseQo;
import com.hilinos.common.util.DateUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class KeyAppImpl implements KeyApp {

    @Autowired
    private KeyInfoService keyInfoService;

    @Override
    public KeyInfoPoJo create(String keyExpTime, Integer keyStatus) {
        return keyInfoService.create(keyExpTime, keyStatus);
    }

    @Override
    public IPage<KeyInfoPoJo> pageList(BaseQo<KeyInfoPoJo, KeyInfoPoJo, KeyInfoPoJo> qo) {
        return keyInfoService.pageList(qo);
    }

    @Override
    public void edit(KeyInfoPoJo keyInfoPoJo) {
        keyInfoService.edit(keyInfoPoJo);
    }

    @Override
    public void del(String appid) {
        keyInfoService.removeById(appid);
    }

    /**
     * 定时轮询过期的key
     */
    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void pollExpireKeys() {
        UpdateWrapper<KeyInfoPoJo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(KeyInfoPoJo::getKeyStatus, KeyInfoPoJo.STATUS_EXPIRE)
                .eq(KeyInfoPoJo::getKeyStatus, KeyInfoPoJo.STATUS_USED)
                .isNotNull(KeyInfoPoJo::getKeyExpTime)
                .gt(KeyInfoPoJo::getKeyExpTime, DateUtils.getDateString());
        keyInfoService.update(updateWrapper);
    }
}
